# task_worker.py
from xhs.db_queue import task_queue
from xhs import common_db
from xhs import xhs_service
from datetime import datetime
from xhs import config
from xhs.my_log import log
from xhs import db_queue


class DeviceWorker:
    def __init__(self, db_device_map, on_exit):
        self.device_id = db_device_map.get("device_id")
        self.app = db_device_map.get("app")
        self.device_name = db_device_map.get("device_name")
        self.device_map = db_device_map
        self._stop = False
        self.on_exit = on_exit  # 回调：线程退出时执行

    def stop(self):
        self._stop = True

    def run(self):
        log(f"[{self.device_name}][{self.device_id}] 线程已启动\n")
        try:
            while not self._stop:
                try:
                    task = task_queue.get(timeout=2)
                except:
                    continue

                red_id = task.get("red_id")
                log(f"[{self.device_name}][{self.device_id}][{red_id}] 开始处理任务 ")

                # 如果发送次数超过10次，则退出线程并更新设备状态为“开启”
                device = common_db.db_device.find_one({"device_id": self.device_id})
                if device and device.get("count", 0) > 9:
                    db_queue.data_device_set_status(self.device_id, "关闭")
                    # log(f"[{self.device_name}][{self.device_id}] [{red_id}] 发送10次数超过限制，已自动退出线程，并且关闭")
                    xhs_service.backTable(self.device_name,self.device_id,red_id,"发送10次数超过限制，已自动退出线程，并且关闭")
                    break

                # 查询数据库，如果已发送则
                red_id_exists = db_queue.check_red_id_exists(red_id)

                reuslt_status = False
                reuslt_str = "无问题"
                if red_id_exists:
                    log(f"[{self.device_name}][{self.device_id}] [{red_id}]小红书id重复,不需要再次发送")
                    common_db.db_source.update_one(
                        {"_id": task["_id"]},
                        {
                            "$set": {
                                config.system + "processed": True,
                                config.system + "processed_time": datetime.utcnow()
                            }
                        }
                    )
                    reuslt_status = True
                    reuslt_str = "重复发送"
                else:
                    # 发送私信
                    reuslt = xhs_service.send_dm(self.device_map, red_id);

                    reuslt_status = reuslt["status"]
                    reuslt_str = reuslt["result"]
                    if (reuslt["status"]):
                        #发送成功更新数据源状态
                        common_db.db_source.update_one(
                            {"_id": task["_id"]},
                            {
                                "$set": {
                                    config.system + "processed": True,
                                    config.system + "processed_time": datetime.utcnow()
                                }
                            }
                        )
                        # 发送成功累加设备发送次数，切换主副清零
                        common_db.db_device.update_one(
                            {"device_id": self.device_id},
                            {"$inc": {
                                "count": 1
                            }}
                        )
                        # 保存发送结果
                        task = {
                            "device_id": self.device_id,
                            "red_id": red_id,
                            "status": reuslt_status,
                            "timestamp": datetime.now(),
                            "system": config.system,
                            "result": reuslt_str
                        }
                        common_db.db_send.insert_one(task)



        finally:
            log(f"[{self.device_name}][{self.device_id}] 任务线程已退出")
            self.on_exit(self.device_id)
